import baseRouter from "./baseRouter";
import {RouteConfig} from '@/types/router'
import React, {useEffect, useState} from "react";
import {useRoutes} from "react-router-dom";
import errorRouter from './errorRouter'
import {wrapSuspense} from './lazyLoad'
import {useSelector} from "react-redux";

import LayoutComponent from '@/layout/index'
import {filterAsyncRoute} from "@/utils/router";

let Home = wrapSuspense(React.lazy(() => import('@/views/home')))


const privateRouter: RouteConfig[] = [];
const requireModules = require.context("./modules", false, /.tsx$/);

interface IRouter {
    [key: string]: RouteConfig[];
}

Object.values(
    requireModules.keys().reduce((modules: IRouter, modulePath) => {
        const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");
        modules[moduleName as keyof IRouter] = requireModules(modulePath).default;
        return modules;
    }, {})
).forEach((r) => {
    privateRouter.push(...r)
});

const dynamicRouter: any = [
    {
        element: <LayoutComponent/>,
        children: [
            {
                path: "home",
                element: <Home/>,
                meta: {
                    title: '首页',
                    icon: 'Lock',
                },
                handle: {
                    title: '首页',
                }
            },
            // ...privateRouter
        ],
    },
]

const Router = () => {
    let {userInfo} = useSelector((state: any) => state.user)

    let [allRoutes, setAllRoutes] = useState<RouteConfig[]>([...baseRouter])

    useEffect(() => {
        if (userInfo) {
            let asyncRoute = filterAsyncRoute(privateRouter, userInfo.routes)
            dynamicRouter[0].children = [...dynamicRouter[0].children, ...asyncRoute];
            setAllRoutes((allRoutes)=>[
                ...allRoutes,
                ...dynamicRouter,
                ...errorRouter
            ])
        }
    }, [userInfo])

    return useRoutes(allRoutes)
}

export default Router


export {dynamicRouter};
